package com.gl.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.commom.constant.OrderFileType;
import com.gl.order.commom.util.Fileutils;
import com.gl.order.commom.util.ImageUtils;
import com.gl.order.entity.TFile;
import com.gl.order.entity.TOrderFile;
import com.gl.order.entity.vo.FileVo;
import com.gl.order.mapper.TFileMapper;
import com.gl.order.mapper.TOrderFileMapper;
import com.gl.order.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: liangSY
 * @Date: 2021/6/26
 * @ClassName: FileServiceImpl
 * @Description: FileServiceImpl描述
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class FileServiceImpl extends ServiceImpl<TFileMapper, TFile> implements FileService {

    @Value("${file.root-path}")
    private String fileRootPath;
    @Value("${file.request-url}")
    private String reqUrl;
    @Value("${file.img.sacle.height}")
    private Integer imgHeight;
    @Value("${file.img.scale.width}")
    private Integer imgWidth;


    TOrderFileMapper orderFileMapper;

    public FileServiceImpl(TOrderFileMapper orderFileMapper) {
        this.orderFileMapper = orderFileMapper;
    }

    @Override
    public void addByOrderFileType(String orderId, String orderNo, List<MultipartFile> files, OrderFileType orderFileType) {
        if (CollectionUtil.isEmpty(files)) {
            return;
        }
        List<TFile> tFiles = new ArrayList<>();
        files.stream().forEach(file -> {
            TFile tFile = uploadFile(file, orderFileType.toString());
            tFiles.add(tFile);
        });
        tFiles.stream().forEach(t -> {
            TOrderFile orderFile = TOrderFile.builder()
                    .fileId(t.getId())
                    .fileType(orderFileType.toString())
                    .orderNo(orderNo)
                    .orderId(orderId)
                    .build();
            orderFileMapper.insert(orderFile);
        });
    }


    public TFile uploadFile(MultipartFile file, String folder) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件上传失败");
        }
        String fileName = file.getOriginalFilename();
        String ext = Fileutils.getExt(fileName);
        String path = "/";
        if (StringUtils.isNotBlank(folder)) {
            path = path + folder + "/";
        }
        String rpath = fileRootPath + File.separator + path;
        File fileDir = new File(rpath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String nFileName = IdUtil.randomUUID() + "." + ext;
        File dest = new File(rpath + nFileName);
        try {
//            file.transferTo(dest);
            ImageUtils.scale(file,rpath + nFileName,imgHeight,imgWidth,ext);
        } catch (IOException e) {
            log.error("文件上传失败 {} " + e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        } catch (Exception e) {
            log.error("文件上传失败 {} " + e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        }
        TFile tFile = TFile.builder()
                .name(nFileName)
                .path(path)
                .ext(ext)
                .rootPath(fileRootPath)
                .folder(folder)
                .build();
        save(tFile);
        return tFile;
    }

    public TFile uploadFile(String filePath, String folder) {
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        String ext = Fileutils.getExt(filePath);
        String path = "/";
        if (StringUtils.isNotBlank(folder)) {
            path = path + folder + "/";
        }
        String rpath = fileRootPath + File.separator + path;
        File fileDir = new File(rpath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String nFileName = IdUtil.randomUUID() + "." + ext;
        try {
            log.info("文件上传 {}" +  rpath + nFileName );
            Fileutils.write(rpath + nFileName, file);
        } catch (IOException e) {
            log.error("文件上传失败 {} " + e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        } catch (Exception e) {
            log.error("文件上传失败 {} " + e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        }
        TFile tFile = TFile.builder()
                .name(nFileName)
                .path(path)
                .ext(ext)
                .rootPath(filePath)
                .folder(folder)
                .build();
        save(tFile);
        return tFile;
    }


    public TFile uploadFileToBase64(String file, String folder) {
        String ext = "png";
        String path = "/";
        if (StringUtils.isNotBlank(folder)) {
            path = path + folder + File.separator;
        }
        String rpath = fileRootPath + File.separator + path;
        File fileDir = new File(rpath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String nFileName = IdUtil.randomUUID() + "." + ext;
        try {
            Fileutils.writeByBasr64(file, rpath + nFileName);
        } catch (IOException e) {
            log.error("文件上传失败 {} " + e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        } catch (Exception e) {
            log.error("文件上传失败 {} " + e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        }
        TFile tFile = TFile.builder()
                .name(nFileName)
                .path(path)
                .ext(ext)
                .rootPath(fileRootPath)
                .folder(folder)
                .build();
        save(tFile);
        return tFile;
    }

    @Override
    public FileVo coverFileVo(TFile file) {
        FileVo vo = new FileVo();
        vo.setId(file.getId());
        String url = reqUrl + file.getPath() + file.getName();
        vo.setUrl(url);
        return vo;
    }

    @Override
    public FileVo coverBbsoluteFileVo(TFile file) {
        FileVo vo = new FileVo();
        vo.setId(file.getId());
        String url = fileRootPath + file.getPath() + file.getName();
        vo.setUrl(url);
        return vo;
    }

    @Override
    public void delFile(TFile file) {
        String filePath = file.getRootPath() + file.getPath() + file.getName();
        if (StringUtils.isNotBlank(filePath)) {
            Fileutils.delete(filePath);
        }
    }

    @Override
    public void delFileById(String fileId) {
        TFile file = getById(fileId);
        String filePath = file.getRootPath() + file.getPath() + file.getName();
        Fileutils.delete(filePath);
        removeById(fileId);
    }

    @Override
    public void delFileByIds(List<String> fileIds) {
        List<TFile> files = listByIds(fileIds);
        if (CollectionUtil.isEmpty(files)) {
            return;
        }
        files.stream().forEach(file -> {
            delFile(file);
        });
        removeByIds(fileIds);
    }

    @Override
    public TFile copy(TFile tfile) {
        String path = fileRootPath + tfile.getPath() + tfile.getName();
        TFile tFile = uploadFile(path, tfile.getFolder());
        return tFile;

    }
}
